<?php

namespace backend\controllers;

use Yii;
use yii\web\Controller;
use yii\data\Sort;
use yii\data\ActiveDataProvider;
use backend\models\service\AdminService as Admin;
use yii\filters\AccessControl;

class AdminController extends Controller {
    
    public $enableCsrfValidation = false;

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
//                    [
//                        'actions' => ['login', 'captcha'],
//                        'allow' => true,
//                        'roles' => ['?'],
//                    ],
                ],
            ],
        ];
    }
    public function actionIndex() {
        $searchModel = new Admin();
        $searchModel->load(Yii::$app->request->queryParams);
        $query = Admin::find()->where(['type' => 2]);
        if($username = Yii::$app->request->get('name')){
            $query->andWhere('username like :name');
            $query->addParams([':name'=>'%'.trim($username).'%']);
        }
        $admin = new \backend\models\Admin();
        $cooperation = $admin->getAdmins(array('type'=>2));
        $channel = $admin->getAdmins(array('type'=>3));
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'defaultPageSize' => 10,
            ]
        ]);
        $dataProvider->setSort(false);
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'cooperation' => $cooperation,
            'channel' => $channel,
            'search' => array(
                'name' => trim($username),
            ),
        ]);
    }

    public function actionCreate() {
        $this->layout = false;
        $model = new Admin();
        if (Yii::$app->request->isPost) {
            $request = Yii::$app->request->post();
            $model->admin_sn = $request['admin_sn'];
            $model->username = $request['username'];
            $info = $model->getAdminByUsername($request['username']);
            if(!empty($info)){
                $ret['code'] = 2;
                $ret['msg'] = '合作方账号已存在';
                return $ret;
            }
            $model->password_hash = $request['password'];
            $model->password_repeat = $request['repassword'];
            $model->remark = $request['remark'];
            $model->create_time = date('Y-m-d H:i:s');
            $model->status = 10;
            $model->type = 2;
            $model->password_hash = Admin::setPassword($request['password']);
            $res = $model->save(false);
            if($res){
                $ret['code'] = 0;
                $ret['msg'] = '保存成功';
            }else{
                $ret['code'] = 1;
                $ret['msg'] = '保存失败';
            }
            return json_encode($ret);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * @param integer $id
     * @return mixed
     */
    public function actionDel($id) {
        $model = $this->findModel($id);
        if ($model->delete()) {
            return $this->redirect(['index']);
        }
    }
    
     /**
     * @param integer $id
     * @return mixed
     */
    public function actionView($id) {
        $searchModel = new Admin();
        $searchModel->load(Yii::$app->request->queryParams);
        $model = $this->findModel($id);
        $query = Admin::find()->where(['pid' => $id,'type' => 3]);
        if($username = Yii::$app->request->get('name')){
            $query->andWhere('username like :name');
            $query->addParams([':name'=>'%'.$username.'%']);
        }
        if($cid = Yii::$app->request->get('cid')){
            $query->andWhere(['id' => $cid]);
        }
        $admin = new \backend\models\Admin();
        $channels = $admin->getAdmins(array('type'=>3,'pid'=>$id));
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'defaultPageSize' => 10,
            ]
        ]);
        
        return $this->render('view', [
            'data' => $model,
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'channels' => $channels,
            'search' => array(
                'name' => trim($username),
                'cid' => $cid,
                'id' => $id
            ),
        ]);
    }
    
    /**
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $this->layout = false;
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post())) {
            $request = Yii::$app->request->post('AdminService');
            $model->admin_sn = $request['admin_sn'];
            $model->username = $request['username'];
            $model->password_hash = $request['password_hash'];
            $model->password_repeat = $request['password_repeat'];
            $model->remark = $request['remark'];
            if($model->password_hash == $model->password_repeat){
                $model->password_hash = Admin::setPassword($request['password_hash']);
                if ($model->save(false)) {
                    Yii::$app->getSession()->setFlash('success', '保存成功');
                } else {
                    Yii::$app->getSession()->setFlash('error', '保存失败');
                }
            }
            return $this->redirect(['index']);
            
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    protected function findModel($id) {
        if (($model = Admin::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionChannelLists(){
        $searchModel = new Admin();
        $searchModel->load(Yii::$app->request->queryParams);
        $name = \Yii::$app->request->get('name');
        if(trim($name)){
            $query = Admin::find()->where(['type' => 3])->andWhere('username like :name')->addParams([':name'=>'%'.$name.'%']);
        }else{
            $query = Admin::find()->where(['type' => 3]);
        }
        $query = $query->orderBy('create_time desc');
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'defaultPageSize' => 10,
            ]
        ]);
        $dataProvider->setSort(false);
        return $this->render('channel-lists', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'search' => array('name'=>$name),
        ]);
    }
    
    /**
     * 分发  合作方&渠道联动
     */
    public function actionGetChannelNums()
    {
        if(\Yii::$app->request->isPost){
            $post = \Yii::$app->request->post();
            $pid = $post['pid'];
            $type = $post['type'];
            $res = Admin::getChannelList($pid, $type);
            $data = '';
            foreach($res as $v){
                $data .= "<option value='{$v['id']}'>{$v['username']}</option>";
            }
            echo $data;
        }
    }
    
    /**
     *  新建渠道 
     * @return type
     */
    public function actionCreateChannel() {
        $this->layout = false;
        $model = new Admin();
        if ($model->load(Yii::$app->request->post())) {
            $request = Yii::$app->request->post('AdminService');
            $model->username = $request['username'];
            $model->password_hash = $model->username."zsly";
            $model->pid = $request['pid'];
            $model->remark = $request['remark'];
            $model->create_time = date('Y-m-d H:i:s');
            $model->status = 10;
            $model->type = 3;
            if ($model->validate()) {
                $model->password_hash = Admin::setPassword($model->username."zsly");
                $model->save(false);
                return $this->redirect(['channel-lists']);
            } else {
                print_r($model->getErrors());
                die;
            }
        } else {
            return $this->render('create-channel', [
                'model' => $model,
            ]);
        }
    }
    
    /**
     * @param integer $id
     * @return mixed
     */
    public function actionDelChannel($id) {
        $model = $this->findModel($id);
        if ($model->delete()) {
            return $this->redirect(['channel-lists']);
        }
    }
    
    /**
     * @param integer $id
     * @return mixed
     */
    public function actionUpdateChannel($id)
    {
        $this->layout = false;
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post())) {
            $request = Yii::$app->request->post('AdminService');
            $model->username = $request['username'];
            $model->cost = $request['cost'];
            $model->remark = $request['remark'];
            if ($model->save(false)) {
                Yii::$app->getSession()->setFlash('success', '保存成功');
            } else {
                Yii::$app->getSession()->setFlash('error', '保存失败');
            }
            return $this->redirect(['channel-lists']);
            
        } else {
            return $this->render('update-channel', [
                'model' => $model,
            ]);
        }
    }
    
    /**
     * @param integer $id
     * @return mixed
     */
    public function actionChannelInfo() {
//        $this->layout = false;
        $get = \Yii::$app->request->get();
        $id = intval($get['id']);
        $params['channel_id'] = $id;
        $params['page'] = isset($get['page']) ? intval($get['page']) : 1;
        $params['pageSize'] = 10;
        $params['name'] = isset($get['name']) ? $get['name'] : '';
        $model = new \backend\models\Tweet();
        $data = $model->getTweetListByChannel($params);
        $channel = \backend\models\Admin::getById($id);
        $data['channel'] = $channel;
        $data['params'] = $params;
        return $this->render('channel-info',$data);
    }
    
   
}
